package com.yips.service.web;

import com.yips.common.exception.ServiceException;
import com.yips.domain.entity.SysUser;
import com.yips.domain.model.LoginUser;
import com.yips.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * @author h2tc01
 * @version 1.0.0
 * 2022/5/10 14:41
 * <p>
 * 登录校验
 */
@Component
public class LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    public LoginUser login(String username, String password) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            //AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
            throw new ServiceException(e.getMessage());
        }
        return (LoginUser) authentication.getPrincipal();
    }
}
